import { useEffect, useRef, useState } from 'react';
import { Button, Table, Form, Select, Input, Space } from 'antd'
import type { ColumnsType } from 'antd/es/table';
import api from '../../../api';
import type { PageParams, User } from '../../../types/api';
import { formatDate } from '../../../utils';
import CreateUser from './CreateUser';
import type { IModalProp } from '../../../types/modal';
import { message, modal } from '../../../utils/AntdGlobal';

export default function UserList() {
    const [form] = Form.useForm()
    const userRef = useRef<IModalProp | null>(null)

    const [userIds, setUserIds] = useState<number[]>([])
    const [data, setData] = useState<User.userItem[]>([])
    const [total, setTotal] = useState(0)
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10
    })
    useEffect(() => {
        getUserList({
            pageNum: pagination.current,
            pageSize: pagination.pageSize
        })
    }, [pagination.current, pagination.pageSize])
    const getUserList = async (params: PageParams) => {
        try {
            const value = form.getFieldsValue()
            const data = await api.getUserList({
                ...value,
                pageNum: params.pageNum,
                pageSize: params.pageSize || pagination.pageSize
            })
            setData(data.list)
            setTotal(data.page.total)
            setPagination({ current: data.page.pageNum, pageSize: data.page.pageSize })
        } catch (error) {
            console.log(error)
        }
    }

    const handleSearch = () => {
        getUserList({
            pageNum: 1,
            pageSize: pagination.pageSize
        })
    }
    const handleReset = () => {
        form.resetFields()
    }
    const handleCreate = () => {
        userRef.current?.open('create')
    }

    const handleEdit = (record: User.editParams) => {
        userRef.current?.open('edit', record)
    }
    const handleDelete = (id: number) => {
        modal.confirm({
            title: "删除确认",
            content: <span>确认删除该用户吗？</span>,
            onOk: () => {
                handleUserDelSubmit([id])
            }
        })
    }

    const handlePatchDelete = () => {
        if (userIds.length === 0) {
            message.error('请选择要删除的用户')
            return
        }
        modal.confirm({
            title: "删除确认",
            content: <span>确认删除所选用户吗？</span>,
            onOk: () => {
                handleUserDelSubmit(userIds)
            }
        })
    }

    const handleUserDelSubmit = async (userIds: number[]) => {
        await api.delUser({
            userIds
        })
        message.success('删除成功')
        setUserIds([])
        getUserList({
            pageNum: 1,
            pageSize: pagination.pageSize
        })
    }

    const columns: ColumnsType<User.userItem> = [
        {
            title: '用户ID',
            dataIndex: 'userId',
            key: 'userId',
            align: 'center'
        },
        {
            title: '用户名称',
            dataIndex: 'userName',
            key: 'userName',
            align: 'center'
        },
        {
            title: '用户邮箱',
            dataIndex: 'userEmail',
            key: 'userEmail',
            align: 'center'
        },
        {
            title: '用户角色',
            dataIndex: 'role',
            key: 'role',
            align: 'center',
            render(role: number) {
                return {
                    0: '超级管理员',
                    1: '管理员',
                    2: '体验管理员',
                    3: '普通用户'
                }[role]
            }
        },
        {
            title: '用户状态',
            dataIndex: 'state',
            key: 'state',
            align: 'center',
            render(state: number) {
                return {
                    1: '在职',
                    2: '离职',
                    3: '试用期'
                }[state]
            },
        },
        {
            title: '注册时间',
            dataIndex: 'createTime',
            key: 'createTime',
            align: 'center',
            render(createTime: string) {
                return formatDate(createTime)
            }
        },
        {
            title: '操作',
            key: 'address',
            align: 'center',
            render: (record) => < Space>
                <Button type='text' onClick={() => handleEdit(record)}>编辑</Button>
                <Button type='text' danger onClick={() => handleDelete(record.userId)}>删除</Button>
            </Space>
        },
    ]
    return (
        <div className='userList'>
            <Form form={form} className="search" layout='inline' initialValues={{ state: 1 }}>
                <Form.Item name='userId' label='用户ID'>
                    <Input placeholder='请输入用户ID' />
                </Form.Item>
                <Form.Item name='userName' label='用户名称'>
                    <Input placeholder='请输入用户名称' />
                </Form.Item>
                <Form.Item name='state' label='状态'>
                    <Select style={{ width: 120 }}>
                        <Select.Option value={0}>所有</Select.Option>
                        <Select.Option value={1}>在职</Select.Option>
                        <Select.Option value={2}>离职</Select.Option>
                        <Select.Option value={3}>试用期</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item>
                    <Button type='primary' className='mr10' onClick={handleSearch}>搜索</Button>
                    <Button type='default' onClick={handleReset}>重置</Button>
                </Form.Item>
            </Form>
            <div className="table">
                <div className="header">
                    <div className="title">用户管理</div>
                    <div className="action">
                        <Button type='primary' onClick={handleCreate}>新增</Button>
                        <Button type='primary' danger onClick={handlePatchDelete}>批量删除</Button>
                    </div>
                </div>
                <Table
                    bordered
                    rowKey='userId'
                    rowSelection={{
                        type: 'checkbox',
                        selectedRowKeys: userIds,
                        onChange: (selectedRowKeys) => {
                            setUserIds(selectedRowKeys as number[])
                        }
                    }}
                    dataSource={data}
                    columns={columns}
                    pagination={{
                        total,
                        position: ['bottomRight'],
                        current: pagination.current,
                        pageSize: pagination.pageSize,
                        showTotal: () => `共${total}条`,
                        onChange: (page, pageSize) => {
                            setPagination({
                                current: page,
                                pageSize
                            })
                        }
                    }}
                />
            </div>
            <CreateUser
                ref={userRef}
                update={() => {
                    getUserList({
                        pageNum: 1,
                        pageSize: pagination.pageSize
                    })
                }}
            />
        </div>
    )
}